<?php
namespace App\Manager;

class Storage
{
    /**
     * @var \redis
     */
    protected $redis;

    const PREFIX = 'rzdt_white_board:';

    // 缓存时间一天
    const LIFE_TIME = 60 *  60 * 24;

    private static $_instance = null;

    private function __construct($config)
    {
//        $this->redis = \Swoole::getInstance()->redis;
        $this->redis = new \Redis();
        $this->redis->connect('127.0.0.1',6379);
        // 初始化内存操作
        $this->config = $config;
    }

    public static function instance($config=[])
    {   
        if (is_null(self::$_instance))
        {
            self::$_instance = new self($config);
        }
        return self::$_instance;
    } 

    function set($key, $value, $lifetime = null)
    {
        return $this->redis->set(self::PREFIX . $key, $value);
    }

    function get($key, $default=false)
    {
        $res = $this->redis->get(self::PREFIX . $key);
        return false === $res ? $default : $res;
    }

    function loadList($key)
    {
        return $this->redis->lrange(self::PREFIX . $key, 0, 
                    $this->redis->llen(self::PREFIX . $key));
    }

    /**
     * 清除键值
     */
    function clearKeys($key)
    {
        $key_arr = $this->redis->keys($key);
        foreach ($key_arr as $v)
        {
            $this->redis->del($v);
        }
    }

    function remove($key) 
    {
        return $this->redis->delete(self::PREFIX . $key);
    }

    /** 以下用于清除无效连接 **/
    function pushUnuseList($client_id)
    {
        $this->sadd(self::PREFIX . ':unuse_list', $client_id);
    }

    function inUnuseLink($client_id)
    {
        return $this->scontains(self::PREFIX . ':unuse_list', $client_id);
    }

    function removeUnuseList($client_id)
    {
        $this->sremove(self::PREFIX . ':unuse_list', $client_id);
    }

    /**
     * 清楚互动答题储存的所有数据，用于临时清楚
     */
    function flushKeys()
    {
        $keys = $this->redis->keys(self::PREFIX . '*');
        $this->redis->del($keys);
    }
    /** 以上用于清除无效连接 **/
    
    function __call($method, $args)
    {
        $args[0] = self::PREFIX . $args[0];
        // var_dump('key_name', $args[0]);
        return call_user_func_array([$this->redis, $method], $args);
    }
}
